<template>
<div id="textPage">
  <vue-particles
      class="login-bg"
      color="#39AFFD"
      :particleOpacity="0.7"
      :particlesNumber="100"
      shapeType="circle"
      :particleSize="4"
      linesColor="#8DD1FE"
      :linesWidth="1"
      :lineLinked="true"
      :lineOpacity="0.4"
      :linesDistance="150"
      :moveSpeed="3"
      :hoverEffect="true"
      hoverMode="grab"
      :clickEffect="true"
      clickMode="push"
  ></vue-particles>

  <el-container style="position: absolute;top:100px;left:50px;right:50px">
  <el-main width="800px" style="margin:50px;">
    <div class="button" style="margin:0" >
      <el-button-group>
        <el-button v-if="!like" type="primary" icon="el-icon-star-off" @click="addLike">点赞</el-button>
        <el-button v-if="like" type="primary" icon="el-icon-star-on" @click="cancelLike">取消点赞</el-button>
        <el-button type="primary" icon="el-icon-warning-outline" @click="open">举报</el-button>
        <el-button type="primary" icon="el-icon-share" @click="copy">分享</el-button>
      </el-button-group>
      &nbsp;

      <el-button-group v-if="writer">
        <el-button type="primary" icon="el-icon-delete" @click="deleteThisArticle">删除</el-button>
      </el-button-group>
    </div>

    <div class="publishid" >
      <div style="margin:10px 0 -5px 30px">发布用户:{{userData.username}}&nbsp;&nbsp;发布时间：{{textData.time}}&nbsp;&nbsp;
        浏览数：{{textData.views}}&nbsp;&nbsp;点赞数：{{textData.likes}}</div>
      <div class="tag-group" style="margin-left: 30px">标签：
        <el-button type="info" v-for="(item) in textData.tags" size="small" @click="searchLabel(item)">{{ item }}
        </el-button>
      </div>
    </div>

    <div class="text">
      <div class="title"><h1>{{textData.title}}</h1></div>
      <div class=body v-html="textData.passage"> </div>
    </div>
    <div v-if="textData.attachFiles.length!==0" style="line-height: 35px;font-size: 20px">
      <span>附件：</span>
      <div v-for="(item) in textData.attachFiles">
        <el-link @click.native="toLink(item.attachmentUrl)" style="line-height: 35px;font-size: 15px">{{item.fileName}}</el-link>
        <el-link @click.native="downloadFile(item.attachmentUrl,item.fileName)" style="line-height: 35px;font-size: 15px">&nbsp;&nbsp;下载</el-link>
      </div>
    </div>

    <div class="reply" style="margin-top: 30px" v-for="(item,num) in reply">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <div style="font-size: 20px">
            {{'回复用户：'+item.userName}}
            <el-button style="float: right;" type="primary" @click="changecommenter(item.userID,item.id,item.userName)">回复</el-button>
          </div>
          <div class="replyinfo">{{(num+1)+'楼'}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{'回复时间：'+item.time}}</div>

        </div>
        <div class="text item"> {{item.content}}
        </div>

        <div class="reply" style="margin:30px 0 0 0px" v-for="(reply) in item.subReplyList">
          <div style="margin:15px 0 0 30px">{{reply.replierName}}&nbsp;&nbsp;回复&nbsp;&nbsp;{{reply.receiverName}}&nbsp;&nbsp;
            <span style="font-size: 10px">{{reply.time}}</span>  <el-button type="text" size="small" @click="changecommenter(reply.replierID,item.id,reply.replierName)">回复</el-button></div>
          <div style="margin:15px 0 0 50px">{{reply.content}}</div>
        </div>
      </el-card>
    </div>

    <div v-if="login">
      <el-input class="input"
          type="textarea"
          :autosize="{ minRows: 5}"
          :placeholder="changeholder"
          v-model="textarea"
      >
      </el-input>
      <el-button type="primary" round style="float: right; margin:10px" @click="sendReply">发表回复</el-button>
      <div v-if="this.type===1"></div><el-button round :disabled="judgeReply" style="float: right; margin:10px" @click="cancelCommit">取消回复</el-button>
    </div>

    <div v-if="!login">
      <el-input class="input"
                type="textarea"
                :autosize="{ minRows: 5}"
                placeholder="请先登录"
                v-model="textarea"
                :disabled="true"
      >
      </el-input>
    </div>

  </el-main>


    <el-aside width="300px" style="margin:50px;top:0"><div>
        <div class="userinfo" style="margin:30px;" >
          <div class="block" >
            <img style="width:100px;height:100px;border-radius: 50%"  :src="circleUrl" ></div>
          <el-link @click.native="toUser(userData.userid)"><h2>{{userData.username}}</h2></el-link>
          <div>粉丝&nbsp;&nbsp;&nbsp;{{userData.followers}}</div>
          <div style="margin:10px">文章&nbsp;&nbsp;&nbsp;{{userData.textnum}}</div>
          <div style="margin:40px">
            <el-button v-if="!this.followed" type="primary" @click="addFollow">关注</el-button>
            <el-button v-if="this.followed" type="info" @click="cancelFollow">取消关注</el-button>
          </div>
        </div>

      <div style="text-align:left;margin:20px"><h3>相关文章推荐：</h3></div>
      <div class="recommend" v-for="count in 5" style="margin:20px">
        <el-link style="font-size:18px" @click.native="toArticle(recommend.id[count-1])">{{recommend.title[count-1]}}</el-link>
      </div>

      <div style="text-align:left;margin:20px"><h3>热门文章：</h3></div>
      <div class="authorPassage" v-for="count in 5" style="margin: 20px;">
        <el-link style="font-size:18px"  @click.native="toArticle(hotpassage.id[count-1])">{{hotpassage.title[count-1]}}</el-link>
      </div>

      <div style="text-align:left;margin:20px"><h3>最新文章：</h3></div>
      <div class="authorPassage" v-for="count in 5" style="margin: 20px;">
        <el-link style="font-size:18px"  @click.native="toArticle(authorpassage.id[count-1])">{{authorpassage.title[count-1]}}</el-link>
      </div>

    </div>
    </el-aside>
  </el-container>

</div>
</template>

<script>

import qs from "qs";
import user from "@/store/user";

export default {
  inject: ['reload'],
  // eslint-disable-next-line vue/multi-word-component-names
  name: "text",
  data () {
    return {
      dialogVisible: false,
      fit:"fill",
      replyholder:'请输入回复',
      followed:false,
      like:false,
      textarea: '',
      circleUrl: "",
      reportReason:'',
      // sizeList: ["large"]
      writer:false,
      login:this.$store.state.isLogin,
      admin:false,
      type:0,
      oldComment: null, //久评论者的名字
      chosedIndex: null, //被选中的评论的index
      replyname:null,
      userData:
        {
          userid:0,
          username:"",
          followers:0,
          textnum:0
        },
      passage:'<p><img style="width:100%" src="http://124.221.200.179/api/img/2022-06-0290809760-747d-4c82-9140-8018d2071715.jpg" alt="微信图片_20220602195717.jpg" /></p>',
      textData:
        {
          title:"",
          passage:'',
          time:"",
          tags:[],
          attachFiles:[],
          likes:0,
          views:0,
        },

      authorpassage:{
        title:[],
        id:[]
      },

      hotpassage:{
        title:[],
        id:[]
      },

      recommend: {
        title: [],
        id: []
      },

      reply:[]
    }
  },

  created(){
    this.getArticle();
  },

  computed: {
    changeholder() {
      if (this.type === 1) return "回复" + this.replyname
      else return "请输入评论"
    },
    judgeReply() {
      return this.type === 0;
    }
  },

  methods: {
    downloadFile:function(link,name) {
      const a = document.createElement("a");
      fetch(link)
          .then((res) => res.blob())
          .then((blob) => {
            // 将链接地址字符内容转变成blob地址
            a.href = URL.createObjectURL(blob);
            console.log(a.href);
            a.download = name; // 下载文件的名字
            document.body.appendChild(a);
            a.click();
          });
    },
    searchLabel(keyword) {
      this.$router.push({path: '/labelSearch', query: {keyword: keyword}})
    },
    toUser: function (id) {
      this.$router.push({path: '/userPage', query: {userID: id}})
    },
    copy: function () {
      var message = window.location.href;
      var that = this
      this.$copyText(message).then(function (e) {
        that.$message.success("已将网址复制到剪切板！");
        console.log(e)
      }, function (e) {
        that.$message.error('分享失败!')
        console.log(e)
      })

    },
    getArticle: function () {
      const userInfo = user.getters.getUser(user.state());
      var userID;
      if (userInfo === null) userID = null;
      else userID = userInfo.user.userID;

      this.$axios({
        method: 'post',
        url: '/article/view',
        data: ({
          viewerID: userID,
          articleID: this.$route.query.passageID
        })
      })
          .then(res => {
            this.userData.userid= res.data.data.author.id
            this.userData.username= res.data.data.author.userAccount
            this.userData.followers=res.data.data.author.followers
            this.userData.textnum=res.data.data.author.articleNum

            this.textData.title=res.data.data.article.title
            this.textData.passage=res.data.data.article.content_html
            this.textData.time=res.data.data.article.createTime
            this.textData.tags=res.data.data.labels
            this.textData.attachFiles=res.data.data.attachmentList
            this.textData.likes=res.data.data.article.likes
            this.textData.views=res.data.data.article.views

            this.authorpassage.title = res.data.data.latestTitles
            this.authorpassage.id =res.data.data.latestIDs

            this.recommend.title = res.data.data.recTitles
            this.recommend.id = res.data.data.recIDs

            this.hotpassage.title = res.data.data.hotTitles
            this.hotpassage.id = res.data.data.hotIDs

            this.followed=res.data.data.isFollow
            this.like=res.data.data.isLike

            this.reply=res.data.data.replyList
            this.circleUrl=res.data.data.author.avatarUrl

            if (this.userData.userid === userID)
              this.writer = true
            this.textData.passage=this.textData.passage.replace(/<img/g,"<img style=\"width:100%\"")
            this.textData.passage=this.textData.passage.replace(/<pre/g,"<pre style=\"width:95%;white-space: pre-wrap;font-size:17px;line-height:30px;background-color: rgba(224, 226, 229, 0.59);\"")
            this.textData.passage=this.textData.passage.replace(/<code/g,"<code style=\"font-family:'Lucida Console';\"")
            this.textData.time=this.textData.time.replace(/T/g," ")
            this.textData.time=this.textData.time.replace(/.000\+00:00/g,"")
            if(this.circleUrl===null)
              this.circleUrl="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
          })
          .catch(err => {
            console.log(err);         /* 若出现异常则在终端输出相关信息 */
          })
    },

    sendReply: function(){
      const userInfo = user.getters.getUser(user.state());
      if(this.$store.state.isBan) {
        this.$message.error("您已被封禁！");
        return;
      }
      this.$axios({
        method: 'post',
        url: '/article/comment',
        data: ({
          articleID:this.$route.query.passageID,
          replierID:userInfo.user.userID,
          receiverID:this.oldComment,
          content:this.textarea,
          toID:this.chosedIndex
        })
      })
            .then(res => {
              if (res.data.code===0) {
                this.$message.success("评论发表成功！");
                this.reload();
              }
              else{
                this.$message.warning("发送失败");
              }
            })
            .catch(err => {
              console.log(err);
            })
    },
    addFollow:function (){
      const userInfo = user.getters.getUser(user.state());
      var userID;
      if (userInfo === null) {
        this.$message.warning("请先登录")
        return
      } else userID = userInfo.user.userID;
      this.$axios({
        method: 'post',
        url: '/user/follow',
        data: ({
          userID: userID,
          authorID: this.userData.userid,
          isFollow:true,
        })
      })
            .then(res => {
              if (res.data.data) {
                this.$message.success("关注成功");
                this.reload();
              }
              else{
                this.$message.warning("关注失败");
              }
            })
            .catch(err => {
              console.log(err);         /* 若出现异常则在终端输出相关信息 */
            })

    },
    cancelFollow:function (){
      const userInfo = user.getters.getUser(user.state());
      var userID;
      if(userInfo===null)
        this.$message.warning("请先登录")
      else userID=userInfo.user.userID;
      this.$axios({
        method: 'post',
        url: '/user/follow',
        data: ({
          userID: userID,
          authorID: this.userData.userid,
          isFollow:false
        })
      })
            .then(res => {
              if (res.data.data) {
                this.$message.success("取消关注成功");
                this.reload();
              }
              else{
                this.$message.warning("取消关注失败");
              }
            })
            .catch(err => {
              console.log(err);         /* 若出现异常则在终端输出相关信息 */
            })
    },
    addLike:function (){
      const userInfo = user.getters.getUser(user.state());
      var userID;
      if (userInfo === null) {
        this.$message.warning("请先登录")
        return
      } else userID = userInfo.user.userID;
      this.$axios({
        method: 'post',
        url: '/user/like',
        data: ({
          userID: userID,
          articleID: this.$route.query.passageID,
          isLike:true
        })
      })
            .then(res => {
              if (res.data.data) {
                this.$message.success("点赞成功");
                this.reload();
              }
              else{
                this.$message.warning("点赞失败");
              }
            })
            .catch(err => {
              console.log(err);         /* 若出现异常则在终端输出相关信息 */
            })
    },
    cancelLike:function (){
      const userInfo = user.getters.getUser(user.state());
      var userID;
      if(userInfo===null)
        this.$message.warning("请先登录")
      else userID=userInfo.user.userID;
      this.$axios({
        method: 'post',
        url: '/user/like',
        data: ({
          userID: userID,
          articleID: this.$route.query.passageID,
          isLike:false
        })
      })
            .then(res => {
              if (res.data.data) {
                this.$message.success("取消点赞成功");
                this.reload();
              }
              else{
                this.$message.warning("取消点赞失败");
              }
            })
            .catch(err => {
              console.log(err);         /* 若出现异常则在终端输出相关信息 */
            })
    },
    toArticle(id){
      this.$router.push({path: '/text', query: {passageID: id}})
      this.reload()
    },
    changecommenter(id,index,name) {
      this.oldComment = id;
      this.chosedIndex = index;
      this.replyname=name;
      this.type = 1;
    },
    //监听到了取消评论
    cancelCommit(){
      this.oldComment=null;
      this.chosedIndex=null;
      this.replyname=null;
      this.type = 0;
    },
    open() {
      this.$prompt('请输入举报理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        this.reportReason=value;
        this.report();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消'
        });
      });
    },
    report:function (){
      const userInfo = user.getters.getUser(user.state());
      var userID;
      if (userInfo === null) {
        this.$message.warning("请先登录")
        return
      } else userID = userInfo.user.userID;
      this.$axios({
        method: 'post',
        url: '/user/report',
        data: ({
          userID: userID,
          articleID: this.$route.query.passageID,
          reason: this.reportReason

        })
      })
          .then(res => {
            window.alert(JSON.stringify(res.data))
            if (res.data.code===0) {
              this.$message.success("举报成功");
              this.reload();
            }
            else{
              this.$message.warning("举报失败");
            }
          })
          .catch(err => {
            console.log(err);         /* 若出现异常则在终端输出相关信息 */
          })
    },
    toLink(link){
      window.open(link,"_blank");
    },
    deleteThisArticle() {
      this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteText()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    deleteText: function () {
      this.$axios({
        method: 'post',
        url: '/article/delete',
        data: ({
          articleID: this.$route.query.passageID,
        })
      })
          .then(res => {
            if (res.data.code === 0)
              this.$message.info("删除成功！")
            this.$router.push('/')
          })
          .catch(err => {
            this.$message.info("删除失败！")        /* 若出现异常则在终端输出相关信息 */
          })
    },

  }
}

</script>



<style scoped>
@import "../assets/font/font.css";

.el-aside {
  background-color: rgba(211, 220, 230, 0.58);
  color: #333;
  text-align: center;
  line-height: 15px;
}

.el-main {
  background-color: rgba(233, 238, 243, 0.59);
  color: #333;
  line-height: 10px;
  text-align: left;
}

.login-bg{
  width: 95%;
  height: 100vh;
}

.title{
  font-size: 30px;
}

.body{
  margin:30px;
  margin-top:50px;
  font-size: 20px;
  line-height: 40px;
  width: 90%;
  max-height: 100%;
}

.publishid{
  background-color: rgba(224, 226, 229, 0.59);
  color: #737373;
  line-height: 40px;
  margin:15px;
}

.text {
  font-size: 15px;
  margin-left: 20px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}

.box-card {
  width: 100%;
}

.replyinfo{
  color: #737373;
  margin-top: 20px;
  font-size: 12px;
}

.input{
  margin-top:30px;
  font-size:18px;
}

.image{
  max-width: 100%;
  height:auto
}

</style>
